package org.zhangxiao.paladin2.common.util;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class DrawUtils {

    public static void saveImage(BufferedImage bufferedImage, String serverPath, float quality) throws IOException {
        File outfile = new File(serverPath);
        if (!outfile.getParentFile().exists()) {
            outfile.getParentFile().mkdirs();
        }
        // 该方法保存图片质量较高
        ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(quality);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(bufferedImage, null, null), iwp);
        writer.dispose();
    }

    /**
     * 将十六进制颜色转换成Color对象
     *
     * @param colorHexStr #FFFFFF
     * @return Color
     */
    public static Color hex2Color(String colorHexStr) {
        if (colorHexStr.startsWith("#")) {
            colorHexStr = colorHexStr.substring(1);
        }
        return new Color(
                Integer.valueOf(colorHexStr.substring(0, 2), 16),
                Integer.valueOf(colorHexStr.substring(2, 4), 16),
                Integer.valueOf(colorHexStr.substring(4, 6), 16));
    }

    public static BufferedImage readImage(String serverPath) throws IOException {
        File f = new File(serverPath);
        return ImageIO.read(f);
    }
}
